<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="90%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="套餐名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入套餐名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="套餐类型" prop="packageType">
            <el-select v-model="formData.packageType" placeholder="请选择套餐类型" class="w100%!">
              <el-option
                v-for="item in packageTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用活动" prop="suitActivity">
            <el-radio-group v-model="formData.suitActivity" class="ml-4">
              <el-radio :label="1" size="large">个人</el-radio>
              <el-radio :label="2" size="large">平台</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 套餐内容 -->

      <el-form-item label="套餐内容" prop="reqVO">
        <el-button :icon="CirclePlus" @click="handleSelectGoods" v-if="formType === 'create'"
          >添加商品</el-button
        >
      </el-form-item>
      <el-divider />
      <el-table :data="goodsList" style="width: 100%">
        <el-table-column prop="productName" label="商品名称" align="center" />
        <el-table-column prop="merchantName" label="所属商家" align="center" />
        <el-table-column prop="address" label="地址" align="center" width="300px" />
        <el-table-column prop="supplyPrice" label="供货价/总" align="center" />
        <el-table-column prop="platformPrice" label="平台售价/人" align="center" />
        <el-table-column prop="productIntroduct" label="商品介绍" align="center">
          <template #default="scope">
            <el-popover
              :width="300"
              popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
            >
              <template #reference>
                <span class="color-blue">查看</span>
              </template>
              <template #default>
                {{ scope.row.productIntroduct }}
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="copiesNum" label="份数" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.copiesNum" :min="1" step-strictly class="w120px!" />
          </template>
        </el-table-column>
      </el-table>

      <el-row class="mt8">
        <el-col :span="12" v-if="formData.suitActivity == 1">
          <el-form-item label="套餐价格(元)/总" prop="price" label-width="140">
            <el-input v-model="formData.price" placeholder="请输入供货价(元)/总" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.suitActivity == 2">
          <el-form-item label="套餐价格(元)/人" prop="price" label-width="140">
            <el-input v-model="formData.price" placeholder="请输入平台套餐价格(元)/人" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 添加商品弹窗：查看 -->
  <Packages ref="formRefPackages" @child-event="handleChildEvent" />
</template>
<script setup lang="ts">
import { CirclePlus } from '@element-plus/icons-vue'
import Packages from './components/Packages.vue'
import * as PackageListApi from '@/api/blind/packageList'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  name: undefined,
  packageType: undefined,
  suitActivity: 1,
  reqVO: [],
  price: undefined,
  status: 1
})
const formRules = reactive({
  name: [{ required: true, message: '套餐名称不能为空', trigger: 'blur' }],
  packageType: [{ required: true, message: '套餐类型不能为空', trigger: 'blur' }],
  suitActivity: [{ required: true, message: '适应活动不能为空', trigger: 'blur' }],
  reqVO: [{ required: true, message: '商品不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '套餐价格不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 商品列表
const goodsList = ref([])

// 商家类型列表
const packageTypeList = ref()

onMounted(async () => {
  const data = await PackageListApi.getPackageInfoListAll()
  packageTypeList.value = data
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await PackageListApi.getPackageInfo(id)
      formData.value = data
      goodsList.value = data.productRespVOList
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  formData.value.reqVO = goodsList.value
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PackageListApi.PackageInfoVO
    if (formType.value === 'create') {
      await PackageListApi.createPackageInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await PackageListApi.updatePackageInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 选择套餐
const formRefPackages = ref()
const handleSelectGoods = () => {
  formRefPackages.value.open()
}

// 父组件回调事件
const handleChildEvent = (dataFromChild) => {
  goodsList.value = dataFromChild
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: undefined,
    packageType: undefined,
    suitActivity: 1,
    reqVO: [],
    price: undefined,
    status: 1
  }
  formRef.value?.resetFields()
  goodsList.value = []
}
</script>
